import {
  Dimensions,
  FlatList,
  GestureResponderEvent,
  LayoutChangeEvent,
  NativeMethods,
  Pressable,
  StyleSheet,
  Text,
  View,
} from "react-native";
import React, {
  useContext,
  useEffect,
  useRef,
  useState,
} from "react";
import { AntDesign } from "@expo/vector-icons";
import { Appbar } from "react-native-paper";
import { useNavigation } from "@react-navigation/native";
import ImageListAuto from "../../components/ImageListAout";
import { Https } from "../../api";
import { ListJsonListItem } from "../../types";
import { GlobalContext } from "../../hooks/reducer";

const width = Dimensions.get("window").width;
const Goods = () => {
  const navigation = useNavigation();

  const changeState: any = useContext(GlobalContext);

  const [currentTargets, setCurrentTargets] =
    useState<Readonly<NativeMethods>>();
  const [actionIndex,setActionIndex] = useState(0)
  const [lists, setLists] = useState();
  const [optionLeftList, setOptionLeftList] = useState<
    Array<LayoutChangeEvent>
  >([]);
  const ScrollView = useRef<any>(null);
  const optionRightList: Array<LayoutChangeEvent> = [];
  useEffect(() => {
    getListJson();
  }, []);

  // useLayoutEffect(() => {

  //   setTimeout(()=>{
  //     console.log(optionLeftList[1]);

  //     optionLeftList[1].currentTarget.setNativeProps({
  //     style: { backgroundColor: "#fff", fontWeight: "800" },
  //   });
  //   },3000)

  // }, []);

  const getListJson = async () => {
    changeState.dispatch({ type: "SetToLoad", payload: true });
    const { status, data } = await Https.getListJson();
    if (status === 200) {
      setLists(data);
      changeState.dispatch({ type: "SetToLoad", payload: false });
    }
  };

  const handleOption = (e: GestureResponderEvent, index: number) => {
    ScrollView.current?.scrollToIndex({ index, viewPosition: 0 });
    const { currentTarget } = e;
    setActionIndex(index)
    // if (currentTarget === currentTargets) return;
    // currentTarget.setNativeProps({
    //   style: { backgroundColor: "#fff", fontWeight: "800" },
    // });
    // currentTargets?.setNativeProps({
    //   style: { backgroundColor: "#f1f1f1", fontWeight: "400" },
    // });
    // setCurrentTargets(currentTarget);
  };

  return (
    <View style={{ flex: 1 }}>
      <Appbar.Header mode="center-aligned" elevated={false}>
        <Appbar.Action
          icon={(props) => <AntDesign name="left" {...props} size={24} />}
          onPress={() => {
            navigation.goBack();
          }}
        />
        <Appbar.Content title="品类列表" titleStyle={styles.title} />
      </Appbar.Header>
      <View style={styles.optionMain}>
        <View style={styles.optionLeftList}>
          <FlatList
            data={lists}
            style={{ width: "100%" }}
            keyExtractor={({ relationIds }) => relationIds}
            renderItem={({ item: { classifyName }, index }) => (
              <Pressable
                style={actionIndex === index && styles.actionBackground }
                onPress={(e) => {
                  handleOption(e, index);
                }}
              >
                <Text
                  style={styles.optionLeftItemText}
                  numberOfLines={1}
                  onLayout={(e) => setOptionLeftList([...optionLeftList, e])}
                >
                  {classifyName}
                </Text>
              </Pressable>
            )}
            horizontal={false}
            showsVerticalScrollIndicator={false}
          />
        </View>
        <View style={styles.optionRightList}>
          <FlatList
            data={lists}
            initialNumToRender={3}
            keyExtractor={({ relationIds }) => relationIds}
            ref={ScrollView}
            renderItem={({ item: { h5Url, list } }) => (
              <View
                style={styles.optionRightItem}
                onLayout={(event) => optionRightList.push(event)}
              >
                <ImageListAuto
                  style={{ height: 90 }}
                  imgUrl={`https://cdn.bestseller.com.cn${h5Url}`}
                />
                <View style={styles.optionRightItemMain}>
                  {list &&
                    list.map(
                      ({
                        createTime,
                        name,
                        miniprogramUrl,
                        classifyId,
                      }: ListJsonListItem) => (
                        <View
                          style={styles.optionRightItemContent}
                          key={createTime}
                        >
                          <Pressable
                            onPress={() => {
                              navigation.navigate("ProductList", {
                                classifyId,
                              });
                            }}
                          >
                            <ImageListAuto
                              style={styles.optionRightItemContentImg}
                              imgUrl={`https://cdn.bestseller.com.cn${miniprogramUrl}`}
                            />
                            <Text style={styles.optionRightItemContentText}>
                              {name}
                            </Text>
                          </Pressable>
                        </View>
                      )
                    )}
                </View>
              </View>
            )}
            horizontal={false}
            showsVerticalScrollIndicator={false}
          />
        </View>
      </View>
    </View>
  );
};

export default Goods;

const styles = StyleSheet.create({
  title: {
    fontSize: 18,
    fontWeight: "500",
  },
  optionMain: {
    flex: 1,
    flexDirection: "row",
  },
  optionLeftList: {
    width: width * 0.2,
    // backgroundColor: '#f1f1f1'
  },
  optionLeftItem: {
    width: "100%",
    height: 50,
    backgroundColor: "#f1f1f1",
  },
  optionLeftItemText: {
    width: width * 0.2,
    height: 50,
    fontSize: 13,
    lineHeight: 50,
    paddingLeft: 5,
    paddingRight: 5,
    textAlign: "center",
    fontWeight: "400",
  },
  optionRightList: {
    flex: 1,
    width: width * 0.8,
    backgroundColor: "#fff",
  },
  optionRightItem: {
    width: "100%",
    padding: 10,
  },
  optionRightItemMain: {
    justifyContent: "space-between",
    flexDirection: "row",
    flexWrap: "wrap",
    marginTop: 10,
  },
  optionRightItemContent: {
    width: width * 0.7 * 0.45,
    marginTop: 20,
  },
  optionRightItemContentImg: {
    // width: '100%',
    height: 150,
    justifyContent: "center",
    alignItems: "center",
  },
  optionRightItemContentText: {
    marginTop: 20,
    textAlign: "center",
  },
  actionBackground:{
    backgroundColor: "#fff", fontWeight: "800"
  }
});
